package com.sky.aspect;


import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect      //表示切面类
@Component   //交给容器管理
@Slf4j       //日志
public class AutoFillAspect {
    @Pointcut("execution( * com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void pt() {
    }

    @Before("pt()")
    public void AutoFill(JoinPoint joinPoint) {
        log.info("公共字段填充");
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AutoFill annotation = method.getAnnotation(AutoFill.class);
        OperationType operationType = annotation.value();

        final val args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }
        final val entry = args[0];
        if (operationType == OperationType.INSERT) {
            try {
                Method setCreatTime = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setUpdateTime = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setCreateUser = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                Method setUpdateUser = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

                //执行方法
                setCreatTime.invoke(entry, LocalDateTime.now());
                setUpdateTime.invoke(entry, LocalDateTime.now());
                setCreateUser.invoke(entry, BaseContext.getCurrentId());
                setUpdateUser.invoke(entry, BaseContext.getCurrentId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            try {
                Method setUpdateTime = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                setUpdateTime.invoke(entry, LocalDateTime.now());
                setUpdateUser.invoke(entry, BaseContext.getCurrentId());
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
